package com.fingard.dsp.bank.directbank.bocz01;

import java.text.DecimalFormat;

import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class BOCZ01BatPayRec extends BOCZ01Base implements IBatPayRec {
    private static final String STR_FORMAT = "000000";
    DecimalFormat decimalFormat = new DecimalFormat(STR_FORMAT);
    //1988
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        return d_BatPayRec(p_req1988);
    }

    //9188
    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        return null;
    }

    //代发工资
    public RetAtsBatPayRec d_BatPayRec(ReqBatPayRec p_reqBat) throws Exception {

        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_reqBat.reqHeader);
        serialNo = p_reqBat.reqHeader.reqSeqID;
        try {
            serviceId = "CBE020202";//代发代报销
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            writeCommonHeader(xmlWriter);
            xmlWriter.writeStartElement("ReqParam");
            xmlWriter.writeElementString("orderFlowNo", serialNo);//need
            xmlWriter.writeElementString("payAccount", p_reqBat.ownAct);//need
            xmlWriter.writeElementString("totalNumber", p_reqBat.totalNum);//need
            xmlWriter.writeElementString("totalAmount", String.valueOf(p_reqBat.getTotalAmt()));//need
            //Todo
            xmlWriter.writeElementString("contractNo", "0");//need 合同号(不知道是什么)
            xmlWriter.writeElementString("transferType", "0");//转账类型 need 默认为0
            xmlWriter.writeElementString("payUse", p_reqBat.useType);
            int count = 1;
            if(Integer.parseInt(p_reqBat.totalNum)>50){
                retAts.respCode = "0";
                retAts.respInfo = "超过代发代报销批量支付最大支持总笔数,最大为50笔";
                retAts.reqSeqID = p_reqBat.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = ConnState.FAIL;
                retAts.writeRetToATS();
                return retAts;
            }
            xmlWriter.writeStartElement("list");
            while (p_reqBat.readRecord()) {
                xmlWriter.writeStartElement("row");
                //Todo 明细编号
                xmlWriter.writeElementString("serialNo",decimalFormat.format(count));
                xmlWriter.writeElementString("employeeId",decimalFormat.format(count));
                xmlWriter.writeElementString("employeeName", p_reqBat.readedDetail.recName);
                xmlWriter.writeElementString("cardNo", p_reqBat.readedDetail.recAct);
                xmlWriter.writeElementString("payAmount", p_reqBat.readedDetail.payAmount);
                xmlWriter.writeElementString("comment", p_reqBat.readedDetail.abstractATS);//传入对账码
                xmlWriter.writeEndElement();
                count++;
            }
            xmlWriter.writeEndElement();
            xmlWriter.writeEndElement();
            xmlWriter.writeEndDocument();//写入报文完成
            String dataConvert = xmlWriter.toXmlString();
            int index = dataConvert.indexOf("?>");
            String data = dataConvert.substring(0,index+2)+"\r\n"+clearLineWrapAndBlank(dataConvert.substring(index+2));
            String[] tmpStrRet = sendToBank(data);//发送银行
            /*tmpStrRet[0]="";
            tmpStrRet[1]="00218000000||#<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                    "<BankData>\n" +
                    "<opRep>\n" +
                    "<opResult>\n" +
                    "<retCode>000000</retCode>\n" +
                    "<retMessage></retMessage>\n+" +
                    "</opResult>\n" +
                    "</opRep>\n" +
                    "</BankData>";*/
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                //解析银行返回 去除后缀无用信息
                /*String retCode = tmpStrRet[1].substring(0,tmpStrRet[1].indexOf("|"));
                String errorMsg = tmpStrRet[1].substring(tmpStrRet[1].indexOf("|")+1,tmpStrRet[1].lastIndexOf("|"));*/
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1].substring(tmpStrRet[1].indexOf("#") + 1), tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpStatus = tmpBkReader.getFirstText("/BankData/opRep/opResult/retCode");
                    String tmpInfo = tmpBkReader.getFirstText("/BankData/opRep/opResult/retMessage");
                    if (tmpStatus != null && tmpStatus.length() > 0) {
                        retAts.respCode = "0";
                        retAts.reqSeqID = p_reqBat.reqBatchNO;
                        retAts.respInfo = tmpInfo;
                        retAts.transState = tmpStatus;
                        retAts.payInfoCode = retAts.transState;
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
                retAts.respCode = "0";
                retAts.respInfo = tmpStrRet[1];
                retAts.reqSeqID = p_reqBat.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = tmpStrRet[0];
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = tmpStrRet[1];
            }

        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.toString();
            e.printStackTrace();
        }
        if (retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_reqBat.reqBatchNO;
        }
        retAts.writeRetToATS();
        return retAts;
    }

    //1998 状态查询
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        return d_QryBatPayRec(p_req1998);
    }

    //9198
    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        return null;
    }

    //工资代付状态查询
    public RetAtsQryBatPayRec d_QryBatPayRec(ReqQryBatPayRec p_reqQryBat) throws Exception {
        //返回ATS的对象
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_reqQryBat.reqHeader);
        serialNo = p_reqQryBat.reqHeader.reqSeqID;
        serviceId = "CBE010104";
        int turnPageBeginPos = 2;
        int turnPageShowNum = 50;
        int tmpNowReadedCount = 0;//已读条数

        boolean tmpQryNext = true;
        while (tmpQryNext) {//分页查询
            XmlTextWriter xmlWriter;
            xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            writeCommonHeader(xmlWriter);//写入通用的头部节点
            xmlWriter.writeStartElement("ReqParam");
            xmlWriter.writeElementString("orderFlowNo", retAts.retHeader.reqSeqID);
            //分页查询
            xmlWriter.writeElementString("turnPageBeginPosTemp", String.valueOf(turnPageBeginPos));
            xmlWriter.writeElementString("turnPageShowNum", String.valueOf(turnPageShowNum));
            xmlWriter.writeEndElement();
            xmlWriter.writeEndDocument();
            try {
                String dataConvert = xmlWriter.toXmlString();
                int index = dataConvert.indexOf("?>");
                String data = dataConvert.substring(0,index+2)+"\r\n"+clearLineWrapAndBlank(dataConvert.substring(index+2));
                String[] tmpStrRet = sendToBank(data);
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    //解析银行返回
                    /*String retCode = tmpStrRet[1].substring(0,tmpStrRet[1].indexOf("|"));
                    String errorMsg = tmpStrRet[1].substring(tmpStrRet[1].indexOf("|")+1,tmpStrRet[1].lastIndexOf("|"));*/
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1].substring(tmpStrRet[1].indexOf("#") + 1), tmpSbMsg);
                    if (tmpBkReader != null) {
                        String retCode = tmpBkReader.getFirstText("/BankData/opRep/opResult/retCode");
                        String errorMsg = tmpBkReader.getFirstText("/BankData/opRep/opResult/retMessage");
                        if (isActiveRetCode(retCode)) {
                            retAts.respCode = "0";
                            retAts.reqSeqID = p_reqQryBat.reqBatchNO;
                            int tmpEachPiCount =0;
                            int pageTotalNum = tmpBkReader.countElement("/BankData/opRep/opResult/turnPageTotalNum");//符合条件的条数
                            if (pageTotalNum > 0) {
                                retAts.writeBeforeDetail();
                                while (tmpBkReader.read("/BankData/opRep/opResult/list/row")) {
                                    tmpEachPiCount++;
                                    RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                                    tmpRetDetail.payAct = tmpBkReader.readedXElement.getSingleText("cardNo");
                                    tmpRetDetail.payAmount = tmpBkReader.readedXElement.getSingleText("payAmount");
                                    tmpRetDetail.result = retCode + "+" + tmpBkReader.readedXElement.getSingleText("orderState");
                                    tmpRetDetail.postScript = tmpBkReader.readedXElement.getSingleText("comment");//加入一个编号来确认这条记录信息
                                    tmpRetDetail.usage = tmpBkReader.readedXElement.getSingleText("comment");
                                    tmpRetDetail.payInfoCode = tmpRetDetail.result;
                                    retAts.writeRetDetail(tmpRetDetail);
                                }
                            } else if (pageTotalNum == 0) {
                                tmpQryNext = false;
                                retAts.respCode = "-1";
                                retAts.respInfo = "状态查询结果为空";
                            }
                            tmpNowReadedCount += tmpEachPiCount;//总记录数
                            if(tmpNowReadedCount < pageTotalNum){
                                turnPageBeginPos = turnPageBeginPos+turnPageShowNum;//改变起始位置查询下一页
                            }
                            else if(tmpNowReadedCount == pageTotalNum){
                                tmpQryNext = false;
                                tmpNowReadedCount = 0;
                                continue;
                            }
                        } else {
                            tmpQryNext = false;
                            retAts.respCode = "-1";
                            retAts.respInfo = errorMsg;
                        }
                    } else {
                        tmpQryNext = false;
                        retAts.respCode = "-1";
                        retAts.respInfo = tmpSbMsg.toString();
                    }
                } else {
                    tmpQryNext = false;
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpStrRet[1];
                }
            } catch (Exception e) {
                retAts.respCode = "-1";
                retAts.respInfo = e.getMessage();
                e.printStackTrace();
            }
        }
        if (retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_reqQryBat.reqBatchNO;
        }
        if (retAts.respCode.equals("-1")) {
            retAts.writeBeforeDetail();
        }
        retAts.writeAfterDetail();
        return retAts;
    }

}
